import React, { useState, useEffect } from 'react';
import { 
  Descriptions, 
  Card, 
  Tag, 
  Button, 
  Space, 
  Avatar,
  Row,
  Col,
  Statistic,
  Divider,
  message,
  Modal,
  Form,
  Input,
  Select,
  InputNumber
} from 'antd';
import { 
  UserOutlined, 
  TrophyOutlined,
  EditOutlined,
  CloseOutlined
} from '@ant-design/icons';
import './StudentDetail.scss';
import { request } from '@/utils/api';

const { Option } = Select;

const StudentDetail = ({ student, onClose }) => {
  const [studentDetail, setStudentDetail] = useState(null);
  const [editVisible, setEditVisible] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [editForm] = Form.useForm();

  useEffect(() => {
    if (student?.id) {
      fetchStudentDetail(student.id);
    }
  }, [student]);

  // 获取学生详情
  const fetchStudentDetail = async (studentId) => {
    try {
      const result = await request(`/student/${studentId}`);
      if (result.code === 200) {
        setStudentDetail(result.data);
      } else {
        message.error(result.message || '获取学生详情失败');
      }
    } catch (error) {
      console.error('获取学生详情失败:', error);
      message.error('网络错误，请稍后重试');
    }
  };

  // 打开编辑弹窗
  const handleEdit = () => {
    if (studentDetail) {
      editForm.setFieldsValue({
        nickname: studentDetail.nickname,
        email: studentDetail.email,
        lesson_fee: studentDetail.lesson_fee,
        status: studentDetail.status,
        gender: studentDetail.gender,
        total_lessons: studentDetail.total_lessons,
        remark: studentDetail.remark
      });
      setEditVisible(true);
    }
  };

  // 提交编辑
  const handleEditSubmit = async (values) => {
    setEditLoading(true);
    try {
      const result = await request(`/student/${studentDetail.id}`, {
        method: 'PUT',
        body: JSON.stringify(values),
      });
      if (result.code === 200) {
        message.success('学生信息更新成功');
        setEditVisible(false);
        fetchStudentDetail(studentDetail.id); // 刷新数据
      } else {
        message.error(result.message || '更新学生信息失败');
      }
    } catch (error) {
      console.error('更新学生信息失败:', error);
      message.error('网络错误，请稍后重试');
    } finally {
      setEditLoading(false);
    }
  };

  if (!studentDetail) {
    return (
      <div className="student-detail">
        <div className="loading">加载中...</div>
      </div>
    );
  }

  return (
    <div className="student-detail">
      {/* 头部信息 */}
      <div className="detail-header">
        <div className="student-basic">
              <Avatar 
                src={studentDetail.avatar} 
                icon={<UserOutlined />}
                size={80}
              />
          <div className="student-info">
            <h2>{studentDetail.nickname || studentDetail.username}</h2>
            <p className="username">@{studentDetail.username}</p>
            <div className="status-tags">
              <Tag color={studentDetail.status === 'active' ? 'green' : 'red'}>
                {studentDetail.status === 'active' ? '活跃' : '非活跃'}
              </Tag>
              <Tag color="blue">Lv.{studentDetail.level || 1}</Tag>
            </div>
          </div>
        </div>
        <div className="header-actions">
          <Space>
            <Button icon={<EditOutlined />} type="primary" onClick={handleEdit}>
              编辑
            </Button>
            <Button icon={<CloseOutlined />} onClick={onClose}>
              关闭
            </Button>
          </Space>
        </div>
      </div>

      <Divider />

      {/* 统计信息 */}
      <Row gutter={16} className="stats-section">
          <Col span={6}>
          <Card>
            <Statistic
              title="等级"
              value={studentDetail.level || 1}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
          </Col>
          <Col span={6}>
          <Card>
            <Statistic
              title="经验值"
              value={studentDetail.experience || 0}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
          </Col>
          <Col span={6}>
          <Card>
            <Statistic
              title="金币"
              value={studentDetail.coin || 0}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
          </Col>
          <Col span={6}>
          <Card>
            <Statistic
              title="签到天数"
              value={studentDetail.sign || 0}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
          </Col>
        </Row>

      <Divider />

      {/* 基本信息 */}
      <Card title="基本信息" className="info-card">
        <Descriptions column={2} bordered>
          <Descriptions.Item label="用户名">
            {studentDetail.username}
          </Descriptions.Item>
          <Descriptions.Item label="昵称">
            {studentDetail.nickname || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="邮箱">
            {studentDetail.email || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="课时费">
            ¥{studentDetail.lesson_fee || 0}
          </Descriptions.Item>
          <Descriptions.Item label="性别">
            {studentDetail.gender === 'male' ? '男' : 
             studentDetail.gender === 'female' ? '女' : '未知'}
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={studentDetail.status === 'active' ? 'green' : 'red'}>
              {studentDetail.status === 'active' ? '活跃' : '非活跃'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="购买课时">
            {studentDetail.total_lessons || 0}
          </Descriptions.Item>
          <Descriptions.Item label="已用课时">
            {studentDetail.used_lessons || 0}
          </Descriptions.Item>
          <Descriptions.Item label="剩余课时">
            {(studentDetail.total_lessons || 0) - (studentDetail.used_lessons || 0)}
          </Descriptions.Item>
          <Descriptions.Item label="注册时间">
            {studentDetail.created_at ? 
              new Date(studentDetail.created_at).toLocaleString() : '-'
            }
          </Descriptions.Item>
        </Descriptions>
      </Card>



      {/* 备注信息 */}
      {studentDetail.remark && (
        <>
          <Divider />
          <Card title="备注信息" className="info-card">
            <p>{studentDetail.remark}</p>
          </Card>
        </>
      )}

      {/* 登录信息 */}
      <Divider />
      <Card title="登录信息" className="info-card">
        <Descriptions column={2} bordered>
          <Descriptions.Item label="最后登录时间">
            {studentDetail.last_login_at ? 
              new Date(studentDetail.last_login_at).toLocaleString() : '从未登录'
            }
          </Descriptions.Item>
          <Descriptions.Item label="最后登录IP">
            {studentDetail.last_login_ip || '-'}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      {/* 编辑学生弹窗 */}
      <Modal
        title="编辑学生信息"
        open={editVisible}
        onCancel={() => setEditVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="nickname"
                label="昵称"
                rules={[
                  { required: true, message: '请输入昵称' }
                ]}
              >
                <Input placeholder="请输入昵称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="lesson_fee"
                label="课时费"
                initialValue={0}
              >
                <InputNumber 
                  placeholder="请输入课时费" 
                  min={0}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select>
                  <Option value="active">活跃</Option>
                  <Option value="inactive">非活跃</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="gender"
                label="性别"
                initialValue="unknown"
              >
                <Select>
                  <Option value="male">男</Option>
                  <Option value="female">女</Option>
                  <Option value="unknown">未知</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="total_lessons"
                label="购买课时"
                initialValue={0}
              >
                <InputNumber 
                  placeholder="请输入购买课时数" 
                  min={0}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="remark"
            label="备注"
          >
            <Input.TextArea 
              placeholder="请输入备注信息" 
              rows={3}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={editLoading}
              >
                确定
              </Button>
              <Button onClick={() => setEditVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StudentDetail; 